import {resolveUrl} from '@/common/utils.js'
const imageRatio = {
	horizontal: { width: 670, height: 447 },
	vertical: { width: 670, height: 890 }
};
export default {
	methods: {
		createCanvas() {
			if (!this.canvas) {
				this.canvas = document.createElement('canvas');
				this.$refs.canvasContainer.$el.appendChild(this.canvas);
			}
			this.canvas.width = this.box.width * this.pixelRatio;
			this.canvas.height = this.box.height * this.pixelRatio;
			return this.canvas.getContext('2d');
		},
		async calc(src) {
			this.$refs.loading.show('生成中');
			const rect = await this.getImageInfo();
			const image = new Image;
			image.setAttribute('crossOrigin', 'anonymous');
			image.onload = () => {
				const {
					width: imageWidth,
					height: imageHeight
				} = image;
				this.image.height = (rect.width * imageHeight) / imageWidth;
				if (this.isShare) {
					this.type = 'share';
				} else {
					if (imageWidth <= imageHeight) {
						this.type = 'vertical';
					} else {
						this.type = 'horizontal';
					}
				}
				const cType = imageRatio[this.type];
				const width = cType.width / this.ratio;
				const height = cType.height / this.ratio;
				const top = (this.height - height) / 2;
				const left = (this.width - width) / 2;
				Object.assign(this.box, {
					width,
					height,
					top,
					left
				});
				this.$refs.loading.hide();
			};
			// image.onerror = e => this.$refs.loading.hide();
			image.onerror = e => {
				console.log(e);
				this.$refs.loading.hide();
			}
			image.src = resolveUrl(src);
			this.img = image;
		},
		async confirm(event) {
			this.$refs.loading.show('裁剪中');
			const ctx = this.createCanvas();
			const {image, box, img, pixelRatio} = this;
			const imgW = image.width * image.scale;
			const imgH = image.height * image.scale;
			let dx = (imgW - box.width) / 2 - image.left;
			let dy = (imgH - box.height) / 2 - image.top;
			// ctx.fillStyle = '#000';
			// ctx.fillRect(0, 0, box.width * pixelRatio, box.height * pixelRatio);
			ctx.save();
			ctx.drawImage(img, -dx * pixelRatio, -dy * pixelRatio, imgW * pixelRatio, imgH * pixelRatio);
			ctx.restore();
			const dataURL = this.canvas.toDataURL('image/png', 1)

			this.$refs.loading.hide();
			this.$emit('update:visible', false);
			this.$emit('confirm', dataURL);
			this.reset();
		}
	}
}
